/*
 * Copyright (c) ycq_work@163.com
 */

package com.mxg.blog.controller.articleAdmin;

import com.mxg.blog.common.CqLogger;
import com.mxg.blog.common.DetermineLogin;
import com.mxg.blog.common.ResultCode;
import com.mxg.blog.entity.Article;
import com.mxg.blog.service.ArticleService;
import com.mxg.blog.service.UserService;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: ycq_work@163.com
 * @DATE: 2023/5/23 18:12
 * 将回收站的文章恢复至草稿箱
 */
@Controller
public class RestoreArticle {
    CqLogger logger = CqLogger.getInstance();

    private final ArticleService articleService;
    private final UserService userService;

    public RestoreArticle(ArticleService articleService,
                         UserService userService)
    {
        this.articleService = articleService;
        this.userService = userService;
    }

    @PostMapping("api/restoreArticle")
    public ResponseEntity<Map<String, Object>> restoreArticle(@RequestBody Map<String, String> requestMap) {
        Map<String, Object> resultMap = new HashMap<>();

        // logger.print(requestMap);

        DetermineLogin determineLogin = DetermineLogin.getInstance(requestMap.get("userAccount"), userService);

        if(determineLogin.startJudge().equals(DetermineLogin.NOT_LOGIN)){
            resultMap.put(ResultCode.code, ResultCode.WRONG_CODE_NOT_LOGIN);
            resultMap.put(ResultCode.message, ResultCode.WRONG_MESSAGE_NOT_LOGIN);
            return ResponseEntity.ok(resultMap);
        }

        String articleIdString = requestMap.get("articleId");

        Integer articleId;

        try{
            articleId = new Integer(articleIdString);
        }catch (Exception e)
        {
            resultMap.put(ResultCode.code, ResultCode.WRONG_CODE_GET_INFORMATION);
            resultMap.put(ResultCode.message, ResultCode.WRONG_MESSAGE_GET_INFORMATION);
            return ResponseEntity.ok(resultMap);
        }

        logger.print(articleId);

        resultMap.put(ResultCode.code, ResultCode.SUCCESS_CODE);

        Article article = articleService.getArticleByArticleId(articleId);
        if(article != null)
        {
            articleService.restoreDraftArticlesToBox(articleId);
        }
        resultMap.put(ResultCode.message, ResultCode.SUCCESS_MESSAGE);

        return ResponseEntity.ok(resultMap);
    }
}
